// index page
// ============

define([ 'zepto', 'iScrollRefresh', 'sui'], function($, iScrollRefresh) {
  return {
    init: function() {
      this.page = 1;
      this.initScroll();
      this.pullDown = true;
    },
    
    initScroll() {
      var that = this;
      var ir = new iScrollRefresh('#scroller-box','#scroller', {
        pullDown: {
          callback: function(param) {
            that.page = 1;
            that.pullDown = true;
            var requestData = that.getResponseData(that.page);
            $.when(requestData).done(function(data) {
              if(data.nomore == "1") {
                ir.pullDownCallBack(param,1)
              } else {
                ir.pullDownCallBack(param)
              }
              
            })
            
          }
        },
        pullUp: {
          callback: function(param) {
            that.page = that.page + 1;
            that.pullDown = false;
            var requestData = that.getResponseData(that.page);
            $.when(requestData).done(function(data) {
              if(data.nomore == "1") {
                ir.pullUpCallBack(param,1)
              } else {
                ir.pullUpCallBack(param)
              }
            })
            
          }
        }
      });
    },
    
    getResponseData: function(page) {
      var that = this, defer = $.Deferred();
      var requestUrl = window.location.search.split("&")[0];
      $.ajax({
        type: 'GET',
        url: window.__CTX__.root + '/credit-mall/products' + requestUrl + '&filter=true&page=' + page,
        success: function(res) {
          var pageData = res.trim();
          
          if(!that.pullDown && pageData) {
            //上拉有值
            $(".scroller").append(pageData)
            defer.resolve({"nomore": 0})
          } else if(!that.pullDown && !pageData) {
            //上拉没有值
          	$(".scroller").append('<li><div class="no-more"><span>你已经很努力了</span></div></li>')
            defer.resolve({"nomore": 1})
          } else if(that.pullDown && pageData) {
            //下拉刷新有值
            $(".scroller").empty().append(pageData)
            defer.resolve({"nomore": 0})
          } else if(that.pullDown && !pageData) {
            //下拉刷新没有值
            defer.resolve({"nomore": 1})
          }
          
        },
        error: function(res) {
          $.toast("请求数据失败")
          defer.resolve()
        }
      
      })
      
      return defer.promise()
      
    }
       
  }
})